/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.huangjianbo.supos.openapi.core;

import java.util.ServiceLoader;

import io.gitee.huangjianbo.supos.openapi.core.config.SuposApiClientConfig;
import io.gitee.huangjianbo.supos.openapi.core.errors.NotFoundApiClientException;

/**
 * 客户端工厂类
 *
 * @author tomcat
 * @version 1.0
 */
public final class SuposApiClientFactory {

    private static volatile SuposApiClient client;
    private static final Object LOCK = new Object();

    /**
     * 获取客户端
     *
     * @return 客户端实例
     */
    public static SuposApiClient getClient(SuposApiClientConfig config) {
        if (client == null) {
            synchronized (LOCK) {
                if (client == null) {
                    ServiceLoader<SuposApiClient> serviceLoader = ServiceLoader.load(SuposApiClient.class);
                    if (serviceLoader.iterator().hasNext()) {
                        client = serviceLoader.iterator().next();
                        client.setGlobalConfig(config);
                    } else {
                        throw new NotFoundApiClientException();
                    }
                }
            }
        }

        return client;
    }
}
